package com.akk.module.avs.service;

import com.akk.module.avs.entity.AvsYbLoan;
import com.akk.module.avs.entity.AvsYbLoanExample;
import com.akk.module.avs.entity.AvsYbLoanStepExample;
import com.akk.module.avs.mapper.AvsYbLoanMapper;
import com.akk.module.avs.mapper.AvsYbLoanStepMapper;
import com.akk.module.avs.mapper.dao.AvsYbLoanDao;
import com.akk.module.avs.mapper.dao.AvsYbLoanStepDao;
import com.akk.module.avs.model.request.AvsYbLoanRequest;
import com.akk.module.avs.model.response.AvsYbLoanRes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AvsYbLoanService {

    @Autowired
    private AvsYbLoanMapper loanMapper;

    @Autowired
    private AvsYbLoanExample loanExample;

    @Autowired
    private AvsYbLoanDao loanDao;

    @Autowired
    private AvsYbLoanStepDao loanStepDao;

    @Autowired
    private AvsYbLoanStepMapper loanStepMapper;

    @Autowired
    private AvsYbLoanStepExample loanStepExample;

    public List<AvsYbLoan> findByParams(Map params){
        loanExample.clear();
        AvsYbLoanExample.Criteria criteria = loanExample.createCriteria();
        if (params.containsKey("typeId"))
            criteria.andLoanTypeIdEqualTo(Long.valueOf(params.get("typeId").toString()));
        if (params.containsKey("appId"))
            criteria.andAppIdEqualTo(params.get("appId").toString());
        if (params.containsKey("status"))
            criteria.andLoanStatusEqualTo(Integer.valueOf(params.get("status").toString()));
        return loanMapper.selectByExample(loanExample);
    }

    public AvsYbLoanRes findById(Long loanId){
        return loanDao.selectByPrimaryKey(loanId);
    }

    @Transactional
    public void save(AvsYbLoanRequest loan) {
        loanDao.insert(loan);
        Map params = new HashMap();
        params.put("loanId",loan.getLoanId());
        params.put("steps",loan.getSteps());
        loanStepDao.insertBatch(params);
    }

    @Transactional
    public void update(AvsYbLoanRequest loan){
        loanMapper.updateByPrimaryKey(loan);
        loanStepExample.clear();
        loanStepExample.createCriteria().andLoanIdEqualTo(loan.getLoanId());
        loanStepMapper.deleteByExample(loanStepExample);
        Map params = new HashMap();
        params.put("loanId",loan.getLoanId());
        params.put("steps",loan.getSteps());
        loanStepDao.insertBatch(params);
    }

    public void delete(Long loanId){
        loanMapper.deleteByPrimaryKey(loanId);
    }

}
